<template>
  <div class="modbus-config">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <el-icon><Connection /></el-icon>
          <span>Modbus配置管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="saveConfig" :loading="saving">
              <el-icon><Check /></el-icon>
              保存配置
            </el-button>
            <el-button @click="resetConfig">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
            <el-button @click="testConnection" :loading="testing">
              <el-icon><Link /></el-icon>
              测试连接
            </el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="modbusConfig"
        :rules="formRules"
        label-width="140px"
        size="default"
      >
        <!-- Modbus TCP配置 -->
        <el-divider content-position="left">
          <el-icon><Monitor /></el-icon>
          Modbus TCP配置
        </el-divider>
        
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="默认超时时间(ms)" prop="modbus_tcp.default_timeout" required>
              <el-input-number
                v-model="modbusConfig.modbus_tcp.default_timeout"
                :min="100"
                :max="10000"
                style="width: 100%"
                placeholder="3000"
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :md="12">
            <el-form-item label="默认端口" prop="modbus_tcp.default_port" required>
              <el-input-number
                v-model="modbusConfig.modbus_tcp.default_port"
                :min="1"
                :max="65535"
                style="width: 100%"
                placeholder="502"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="连接重试次数" prop="modbus_tcp.connection_retry_count">
              <el-input-number
                v-model="modbusConfig.modbus_tcp.connection_retry_count"
                :min="1"
                :max="10"
                style="width: 100%"
                placeholder="3"
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :md="12">
            <el-form-item label="重试间隔(ms)" prop="modbus_tcp.connection_retry_interval">
              <el-input-number
                v-model="modbusConfig.modbus_tcp.connection_retry_interval"
                :min="100"
                :max="5000"
                style="width: 100%"
                placeholder="1000"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="读取超时(ms)" prop="modbus_tcp.read_timeout">
              <el-input-number
                v-model="modbusConfig.modbus_tcp.read_timeout"
                :min="1000"
                :max="30000"
                style="width: 100%"
                placeholder="5000"
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :md="12">
            <el-form-item label="写入超时(ms)" prop="modbus_tcp.write_timeout">
              <el-input-number
                v-model="modbusConfig.modbus_tcp.write_timeout"
                :min="1000"
                :max="30000"
                style="width: 100%"
                placeholder="3000"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="最大并发连接数" prop="modbus_tcp.max_concurrent_connections">
          <el-input-number
            v-model="modbusConfig.modbus_tcp.max_concurrent_connections"
            :min="1"
            :max="50"
            style="width: 300px"
            placeholder="10"
          />
          <span class="form-tip">建议不超过20</span>
        </el-form-item>

        <!-- Modbus RTU/RS485配置 -->
        <el-divider content-position="left">
          <el-icon><Cpu /></el-icon>
          Modbus RTU (RS485)配置
        </el-divider>
        
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="默认串口设备" prop="modbus_rtu.default_device">
              <el-select v-model="modbusConfig.modbus_rtu.default_device" style="width: 100%" filterable allow-create>
                <el-option label="/dev/ttyUSB0" value="/dev/ttyUSB0" />
                <el-option label="/dev/ttyUSB1" value="/dev/ttyUSB1" />
                <el-option label="/dev/ttyAMA0" value="/dev/ttyAMA0" />
                <el-option label="/dev/ttyS0" value="/dev/ttyS0" />
                <el-option label="/dev/ttyS1" value="/dev/ttyS1" />
                <el-option label="COM1" value="COM1" />
                <el-option label="COM2" value="COM2" />
                <el-option label="COM3" value="COM3" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :md="12">
            <el-form-item label="默认波特率" prop="modbus_rtu.default_baudrate" required>
              <el-select v-model="modbusConfig.modbus_rtu.default_baudrate" style="width: 100%">
                <el-option label="1200" :value="1200" />
                <el-option label="2400" :value="2400" />
                <el-option label="4800" :value="4800" />
                <el-option label="9600" :value="9600" />
                <el-option label="19200" :value="19200" />
                <el-option label="38400" :value="38400" />
                <el-option label="57600" :value="57600" />
                <el-option label="115200" :value="115200" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="校验位" prop="modbus_rtu.default_parity" required>
              <el-select v-model="modbusConfig.modbus_rtu.default_parity" style="width: 100%">
                <el-option label="无校验(N)" value="N" />
                <el-option label="奇校验(O)" value="O" />
                <el-option label="偶校验(E)" value="E" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :md="12">
            <el-form-item label="数据位" prop="modbus_rtu.default_data_bits" required>
              <el-select v-model="modbusConfig.modbus_rtu.default_data_bits" style="width: 100%">
                <el-option label="7位" :value="7" />
                <el-option label="8位" :value="8" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="停止位" prop="modbus_rtu.default_stop_bits" required>
              <el-select v-model="modbusConfig.modbus_rtu.default_stop_bits" style="width: 100%">
                <el-option label="1位" :value="1" />
                <el-option label="2位" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :md="12">
            <el-form-item label="帧间延迟(ms)" prop="modbus_rtu.frame_delay">
              <el-input-number
                v-model="modbusConfig.modbus_rtu.frame_delay"
                :min="1"
                :max="100"
                style="width: 100%"
                placeholder="20"
              />
              <span class="form-tip">字符间隔时间</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="响应超时(ms)" prop="modbus_rtu.response_timeout">
              <el-input-number
                v-model="modbusConfig.modbus_rtu.response_timeout"
                :min="100"
                :max="5000"
                style="width: 100%"
                placeholder="1000"
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :md="12">
            <el-form-item label="RTU重试次数" prop="modbus_rtu.connection_retry_count">
              <el-input-number
                v-model="modbusConfig.modbus_rtu.connection_retry_count"
                :min="1"
                :max="10"
                style="width: 100%"
                placeholder="3"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 功能码配置 -->
        <el-divider content-position="left">
          <el-icon><Grid /></el-icon>
          Modbus功能码配置
        </el-divider>
        
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="支持的功能码">
              <el-checkbox-group v-model="enabledFunctionCodes">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-checkbox :value="1" @change="toggleFunctionCode(1)">
                      读线圈(01)
                    </el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox :value="2" @change="toggleFunctionCode(2)">
                      读离散输入(02)
                    </el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox :value="3" @change="toggleFunctionCode(3)">
                      读保持寄存器(03)
                    </el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox :value="4" @change="toggleFunctionCode(4)">
                      读输入寄存器(04)
                    </el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox :value="5" @change="toggleFunctionCode(5)">
                      写单个线圈(05)
                    </el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox :value="6" @change="toggleFunctionCode(6)">
                      写单个寄存器(06)
                    </el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox :value="15" @change="toggleFunctionCode(15)">
                      写多个线圈(15)
                    </el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox :value="16" @change="toggleFunctionCode(16)">
                      写多个寄存器(16)
                    </el-checkbox>
                  </el-col>
                </el-row>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 通用配置 -->
        <el-divider content-position="left">
          <el-icon><Setting /></el-icon>
          通用配置
        </el-divider>
        
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="轮询间隔(ms)" prop="general.poll_interval" required>
              <el-input-number
                v-model="modbusConfig.general.poll_interval"
                :min="1000"
                :max="60000"
                style="width: 100%"
                placeholder="5000"
              />
              <span class="form-tip">建议5秒以上</span>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :md="12">
            <el-form-item label="错误阈值" prop="general.error_threshold">
              <el-input-number
                v-model="modbusConfig.general.error_threshold"
                :min="1"
                :max="20"
                style="width: 100%"
                placeholder="5"
              />
              <span class="form-tip">连续错误次数</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="重连延迟(ms)" prop="general.reconnect_delay">
              <el-input-number
                v-model="modbusConfig.general.reconnect_delay"
                :min="1000"
                :max="60000"
                style="width: 100%"
                placeholder="5000"
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :md="12">
            <el-form-item label="最大寄存器数" prop="general.max_register_count">
              <el-input-number
                v-model="modbusConfig.general.max_register_count"
                :min="1"
                :max="2000"
                style="width: 100%"
                placeholder="125"
              />
              <span class="form-tip">单次读取数量</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="启用日志" prop="general.enable_logging">
          <el-switch 
            v-model="modbusConfig.general.enable_logging"
            active-text="启用"
            inactive-text="禁用"
          />
          <span class="form-tip">记录Modbus通信日志</span>
        </el-form-item>

        <el-form-item label="日志级别" prop="general.log_level" v-if="modbusConfig.general.enable_logging">
          <el-select v-model="modbusConfig.general.log_level" style="width: 200px">
            <el-option label="DEBUG" value="DEBUG" />
            <el-option label="INFO" value="INFO" />
            <el-option label="WARN" value="WARN" />
            <el-option label="ERROR" value="ERROR" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  Connection, Check, RefreshLeft, Link, Monitor, Cpu, Setting,
  Grid
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { configAPI, modbusAPI } from '@/utils/api'

// 表单引用
const formRef = ref()

// 响应式数据
const saving = ref(false)
const testing = ref(false)
const enabledFunctionCodes = ref([1, 2, 3, 4, 5, 6, 15, 16])

// Modbus配置数据
const modbusConfig = reactive({
  modbus_tcp: {
    default_timeout: 3000,
    default_port: 502,
    connection_retry_count: 3,
    connection_retry_interval: 1000,
    read_timeout: 5000,
    write_timeout: 3000,
    max_concurrent_connections: 10
  },
  modbus_rtu: {
    default_device: '/dev/ttyUSB0',
    default_baudrate: 9600,
    default_parity: 'N',
    default_data_bits: 8,
    default_stop_bits: 1,
    default_timeout: 3000,
    connection_retry_count: 3,
    connection_retry_interval: 1000,
    read_timeout: 5000,
    write_timeout: 3000,
    frame_delay: 20,
    response_timeout: 1000
  },
  general: {
    poll_interval: 5000,
    error_threshold: 5,
    reconnect_delay: 5000,
    max_register_count: 125,
    enable_logging: true,
    log_level: 'INFO'
  },
  function_codes: {
    read_coils: 1,
    read_discrete_inputs: 2,
    read_holding_registers: 3,
    read_input_registers: 4,
    write_single_coil: 5,
    write_single_register: 6,
    write_multiple_coils: 15,
    write_multiple_registers: 16
  }
})


// 原始配置备份
let originalConfig = {}

// 表单验证规则
const formRules = {
  'modbus_tcp.default_timeout': [
    { required: true, message: '请输入超时时间', trigger: 'blur' },
    { type: 'number', min: 100, max: 10000, message: '超时时间范围100-10000ms', trigger: 'blur' }
  ],
  'modbus_tcp.default_port': [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口号范围1-65535', trigger: 'blur' }
  ],
  'modbus_rtu.default_baudrate': [
    { required: true, message: '请选择波特率', trigger: 'change' }
  ],
  'modbus_rtu.default_parity': [
    { required: true, message: '请选择校验位', trigger: 'change' }
  ],
  'modbus_rtu.default_data_bits': [
    { required: true, message: '请选择数据位', trigger: 'change' }
  ],
  'modbus_rtu.default_stop_bits': [
    { required: true, message: '请选择停止位', trigger: 'change' }
  ],
  'general.poll_interval': [
    { required: true, message: '请输入轮询间隔', trigger: 'blur' },
    { type: 'number', min: 1000, max: 60000, message: '轮询间隔范围1000-60000ms', trigger: 'blur' }
  ]
}

// 方法
const loadConfig = async () => {
  try {
    const config = await configAPI.getModbusConfig()
    Object.assign(modbusConfig, config)
    originalConfig = JSON.parse(JSON.stringify(config))
    
    // 设置功能码状态
    if (config.function_codes) {
      enabledFunctionCodes.value = Object.values(config.function_codes)
    }
  } catch (error) {
    ElMessage.error('加载Modbus配置失败: ' + error.message)
  }
}

const saveConfig = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    saving.value = true
    
    await configAPI.updateModbusConfig(modbusConfig)
    originalConfig = JSON.parse(JSON.stringify(modbusConfig))
    
    ElMessage.success('Modbus配置保存成功')
  } catch (error) {
    ElMessage.error('保存Modbus配置失败: ' + error.message)
  } finally {
    saving.value = false
  }
}

const resetConfig = () => {
  ElMessageBox.confirm(
    '确定要重置Modbus配置吗？所有未保存的修改将丢失。',
    '重置确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    Object.assign(modbusConfig, JSON.parse(JSON.stringify(originalConfig)))
    formRef.value?.clearValidate()
    ElMessage.success('配置已重置')
  }).catch(() => {
    // 用户取消
  })
}

const testConnection = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) {
      ElMessage.warning('请先完善配置信息')
      return
    }

    testing.value = true

    // 使用真实的API测试Modbus连接
    const result = await modbusAPI.testConnection(modbusConfig)

    if (result.success) {
      ElMessage.success('Modbus配置测试成功')
    } else {
      ElMessage.error('Modbus配置测试失败: ' + result.message)
    }
  } catch (error) {
    ElMessage.error('Modbus配置测试失败: ' + error.message)
  } finally {
    testing.value = false
  }
}

// 功能码管理
const toggleFunctionCode = (code) => {
  if (enabledFunctionCodes.value.includes(code)) {
    enabledFunctionCodes.value = enabledFunctionCodes.value.filter(fc => fc !== code)
  } else {
    enabledFunctionCodes.value.push(code)
  }
}


// 生命周期
onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.modbus-config {
  max-width: 1200px;
  margin: 0 auto;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.header-actions {
  margin-left: auto;
  display: flex;
  gap: 12px;
}

.form-tip {
  color: #8c8c8c;
  font-size: 12px;
  margin-left: 8px;
}

.test-result-card {
  margin-top: 20px;
}

:deep(.el-divider__text) {
  background-color: var(--el-bg-color);
  padding: 0 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input-number) {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .header-actions .el-button {
    width: 100%;
  }
}
</style>